#!/usr/bin/env python
# -*- coding:utf-8 -*-

import wmi,time,subprocess,gevent
from .openssh import Win_shell
# from gevent import monkey;monkey.patch_all()

# monkey;monkey.patch_all() # 遇到耗时的操作（阻塞），monkey.patch_all()将耗时的操作自动转换gevent的异步操作
# monkey.patch_all(thread=False, socket=False, select=False)

class Win32Info (object):
    def __init__ (self,ip):
        self.ip = ip 
        self.wmi_obj = self.ping_ip ()
        
    def ping_ip (self):
        try:
            res = subprocess.call ('ping -n 1 -w 5 %s' % self.ip,stdout=subprocess.PIPE) # windows 
            # res = subprocess.call ('ping -n 1 -w 5 %s' % ip,stdout=subprocess.PIPE,shell = True) # linux
            
            if res == False:
                # ip_list.append (self.ip)
                wmi_obj = wmi.WMI (computer = self.ip,user = r'.\admin',password = '2018.pw.')
                if wmi_obj:
                    return wmi_obj
                    
        except:
            pass

    def c_disk (self,x):
        if x > 0.9:
            return 1
        else:
            return 0

        
    def collect (self):
        c_disk = self.wmi_obj.Win32_LogicalDisk (Caption = 'C:')[0]
        c_free = int(c_disk.FreeSpace) / int (c_disk.Size) # 显示C盘空闲比例'
        if  self.wmi_obj.Win32_Process (name="ccSvcHst.exe"):
            ccSvcHst = 0
        else:
            ccSvcHst = 1

        cmd = r'cmd /c net use \\172.25.1.170\temp\txt Aa123456 /user:atl-bm\admin-106519 & quser >> \\172.25.1.170\temp\txt\{}.txt'.format(
            self.wmi_obj.Win32_ComputerSystem()[0].Name)
        self.wmi_obj.Win32_Process.Create(CommandLine=cmd)  # 获取每台电脑当前登录用户

        Win_shell(self.ip).open_ssh()  # 每个windows电脑建立ssh连接

        data = {
            'os_name':self.wmi_obj.Win32_ComputerSystem()[0].Name, # 显示系统名称 'SIT-I44987-O'
            'os_system':self.wmi_obj.Win32_OperatingSystem()[0].Name [:24], # 显示操作系统 'Microsoft Windows 10
            'ip':self.ip,
            'c_disk':self.c_disk(c_free),
            'ccSvcHst':ccSvcHst,
            }
            
        # 分别获取各种硬件信息
        data.update (self.get_cpu_info()) # 更新键值 
        data.update (self.get_ram_info())
        # data.update (self.get_motherboard_info())
        data.update (self.get_disk_info())
        data.update (self.get_nic_info())
        # 最后返回一个数据字典
        return data
    
    def get_cpu_info (self):
        """
        获取CPU的相关数据，这里只采集了三个数据，实际有更多，请自行选择需要的数据
        :return:
        """
        data = {}
        cpu_lists = self.wmi_obj.Win32_Processor()
        cpu_core_count = 0
        for cpu in cpu_lists:
            cpu_core_count += cpu.NumberOfCores
            
        cpu_model = cpu_lists[0].Name # CPU型号（所有的CPU型号都是一样的）
        data ['cpu_cont'] = len (cpu_lists)  # CPU个数
        data ['cpu_model'] = cpu_model
        data ['cpu_core_count'] = cpu_core_count # CPU总的核数
        return data
        
    def get_ram_info (self):
        """
        收集内存信息
        :return:
        """
        data = []
        ram_collections = self.wmi_obj.Win32_PhysicalMemory()
        for ram in ram_collections:  # 主机中存在很多根内存，要循环所有的内存数据
            ram_size = int (int (ram.Capacity) / (1024**3)) # 转换内存单位为GB
            item_data = {
                'slot':ram.DeviceLocator.strip(),
                'capacity':ram_size,
                'model':ram.Caption,
                'manufacturer':ram.Manufacturer,
                'sn':ram.SerialNumber
                }
            data.append (item_data)  # 将每条内存的信息，添加到一个列表里
        return {'ram':data}   # 再对data列表封装一层，返回一个字典，方便上级方法的调用
        
    # def get_motherboard_info (self):
        # """
        # 获取主板信息
        # :return:
        # """
        # computer_info  = self.wmi_obj.Win32_ComputerSystem ()[0]
        # system_info = self.wmi_obj.Win32_OperatingSystem ()[0]
        # data = {}
        # data ['manufacturer'] = computer_info.Manufacturer
        # data ['model'] = computer_info.Model
        # data ['wake_up_type'] = computer_info.WakeUpType
        # data ['sn'] = system_info.SerialNumber
        # return data

    def get_disk_info (self):
        """
        硬盘信息
        :return:
        """
        data = []
        for disk in self.wmi_obj.Win32_DiskDrive ():  # 每块硬盘都要获取相应信息
            disk_data = {}
            interface_choices = ['SAS','SCSI','SATA','SSD']
            for interface in interface_choices:
                if interface in disk.Model:
                    disk_data ['interface_type'] = interface
                    break 
                else:
                    disk_data ['interface_type'] = 'unknown'
                
            disk_data ['slot'] = disk.index
            disk_data ['sn'] = disk.SerialNumber
            disk_data ['model'] = disk.Model
            disk_data ['manufacturer'] = disk.Manufacturer
            disk_data ['capacity'] =int (int (disk.Size) / (1024 **3))
            data.append (disk_data)
        
        return {'physical_disk_driver':data}
        
    def get_nic_info (self):
        """
        网卡信息
        :return:
        """
        data = []
        for nic in self.wmi_obj.Win32_NetworkAdapterConfiguration():
            if nic.MACAddress is not None:
                nic_data = {}
                nic_data['mac'] = nic.MACAddress
                nic_data ['model'] = nic.Caption
                nic_data['name'] = nic.Index
                if nic.IPAddress is not None:
                    nic_data ['ip_address'] = nic.IPAddress[0]
                    nic_data ['net_mask'] = nic.IPSubnet
                else:
                    nic_data ['ip_address'] = ''
                    nic_data ['net_mask'] = ''
                data.append (nic_data)
            
        return {'nic':data}
        

if __name__ == '__main__':
    # 测试代码
    data = Win32Info('172.25.1.105').collect()
        
    for key in data:
        print (key,':',data [key])
        

            
                    
                    
